// 引入 Element Plus 样式
import 'element-plus/dist/index.css';

import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';

import App from './App.vue';
import routes from './router';

// 声明全局属性类型
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $getGlobalState?: () => any;
    $setGlobalState?: (state: any) => void;
    $messageService?: any;
    $stateManager?: any;
    $loadingManager?: any;
    $dataCache?: any;
    $performanceMonitor?: any;
  }
}

let app: any = null;
let router: any = null;
let history: any = null;

// 微应用服务实例
let messageService: any = null;
let stateManager: any = null;
let errorHandler: any = null;
let loadingManager: any = null;
let performanceMonitor: any = null;
let dataCache: any = null;

/**
 * 初始化微前端服务
 */
async function initMicroServices(isQiankun: boolean) {
  console.log('[LoginApp] 初始化微前端服务...');

  if (isQiankun) {
    // Qiankun 环境：从主应用获取服务
    messageService = (window as any).__MICRO_MESSAGE_SERVICE__;
    stateManager = (window as any).__MICRO_GLOBAL_STATE__;
    loadingManager = (window as any).__MICRO_LOADING_MANAGER__;
    dataCache = (window as any).__MICRO_DATA_CACHE__;
    performanceMonitor = (window as any).__MICRO_PERFORMANCE_MONITOR__;

    console.log('[LoginApp] ✅ 从主应用获取服务:', {
      messageService: !!messageService,
      stateManager: !!stateManager,
      loadingManager: !!loadingManager,
      dataCache: !!dataCache,
      performanceMonitor: !!performanceMonitor,
    });
  } else {
    // 独立运行：创建本地服务实例
    const { createMessageService } = await import('@tuxing/core-message-service');
    const { createStateManager } = await import('@tuxing/core-state-manager');
    const { createLoadingManager } = await import('@tuxing/core-loading-manager');
    const { createPerformanceMonitor } = await import('@tuxing/core-performance-monitor');
    const { createDataCache } = await import('@tuxing/core-data-cache');

    messageService = createMessageService({
      appName: 'login-app',
      debug: true,
    });

    stateManager = createStateManager({
      enablePersistence: true,
      debug: true,
    });
    stateManager.init();

    loadingManager = createLoadingManager({
      debug: true,
    });

    performanceMonitor = createPerformanceMonitor({
      appName: 'login-app',
      enabled: true,
      debug: true,
    });

    dataCache = createDataCache({
      strategy: 'hybrid',
      debug: true,
    });

    console.log('[LoginApp] ✅ 独立模式：已创建本地服务实例');
  }

  // 创建错误处理器（无论哪种模式都需要）
  const { createErrorHandler } = await import('@tuxing/core-error-handler');
  errorHandler = createErrorHandler({
    appName: 'login-app',
    enabled: true,
    sendToSentry: false, // 主应用统一上报
    logToConsole: true,
    debug: true,
  });

  // 订阅错误，通过消息服务上报
  if (messageService) {
    errorHandler.subscribe((errorInfo: any) => {
      messageService.broadcast('micro:error', errorInfo);
    });
  }

  console.log('[LoginApp] ✅ 错误处理器已创建');
}

// 微应用生命周期钩子
export async function bootstrap() {
  console.log('[LoginApp] bootstrap 开始');
  // bootstrap 阶段通常用于初始化全局配置
  return Promise.resolve();
}

export async function mount(props: any) {
  console.log('[LoginApp] props from main framework', props);

  // 🔧 修复：如果已有实例，先卸载
  if (app) {
    try {
      console.log('[LoginApp] 发现已存在的实例，先卸载...');
      app.unmount();
    } catch (error) {
      console.warn('[LoginApp] 卸载旧实例时出错:', error);
    }
    app = null;
  }

  // 初始化微前端服务
  await initMicroServices(!!window.__POWERED_BY_QIANKUN__);

  // 创建路由实例
  history = createWebHistory(props.routerBase || '/');
  router = createRouter({
    history,
    routes,
  });

  // 创建应用实例
  app = createApp(App);

  // 配置应用
  const pinia = createPinia();
  app.use(pinia);
  app.use(router);
  app.use(ElementPlus);

  // 注入全局属性用于组件访问
  app.config.globalProperties.$getGlobalState = props.getGlobalState;
  app.config.globalProperties.$setGlobalState = props.setGlobalState;
  app.config.globalProperties.$messageService = messageService;
  app.config.globalProperties.$stateManager = stateManager;
  app.config.globalProperties.$loadingManager = loadingManager;
  app.config.globalProperties.$dataCache = dataCache;
  app.config.globalProperties.$performanceMonitor = performanceMonitor;

  // 挂载应用
  let container;
  if (props.container) {
    if (typeof props.container === 'string') {
      container = document.querySelector(props.container);
    } else if (props.container.querySelector) {
      container = props.container;
    } else {
      container = props.container;
    }
  } else {
    container = document.getElementById('login-app') || document.body;
  }

  // 🔧 修复：如果是 body，创建一个专用容器
  if (container === document.body) {
    let loginContainer = document.getElementById('login-app');
    if (!loginContainer) {
      loginContainer = document.createElement('div');
      loginContainer.id = 'login-app';
      document.body.appendChild(loginContainer);
    }
    // 清空容器内容（确保干净挂载）
    loginContainer.innerHTML = '';
    container = loginContainer;
  }

  console.log('[LoginApp] Mounting to container:', container);
  app.mount(container);

  console.log('[LoginApp] ✅ 应用挂载完成，所有服务已就绪！');
}

export async function unmount() {
  console.log('[LoginApp] unmounted');

  if (app) {
    try {
      app.unmount();
    } catch (error) {
      console.warn('[LoginApp] Error during unmount:', error);
    }
    app = null;
  }

  if (history) {
    history = null;
  }

  if (router) {
    router = null;
  }

  // 销毁本地创建的服务（如果是独立模式）
  if (!window.__POWERED_BY_QIANKUN__ && errorHandler) {
    errorHandler.destroy();
  }
}

// 独立运行时的逻辑
if (!window.__POWERED_BY_QIANKUN__) {
  const mockGlobalState = {
    user: null,
    token: '',
    isLogin: false,
  };

  const mockMessageService = {
    broadcast: (event: string, data: any) => {
      console.log(`[MockMessageService] Broadcasting ${event}:`, data);
    },
    subscribe: (event: string, _callback: (data: any) => void) => {
      console.log(`[MockMessageService] Subscribed to ${event}`);
    },
    unsubscribe: (event: string) => {
      console.log(`[MockMessageService] Unsubscribed from ${event}`);
    },
  };

  mount({
    routerBase: '/',
    container: document.body,
    getGlobalState: () => mockGlobalState,
    setGlobalState: (state: any) => {
      Object.assign(mockGlobalState, state);
      console.log('[MockGlobalState] State updated:', mockGlobalState);
    },
    messageService: mockMessageService,
  });
} else {
  console.log('[LoginApp] Running in qiankun environment');
}

// 确保生命周期方法在全局可访问（给 qiankun 使用）
declare global {
  interface Window {
    __POWERED_BY_QIANKUN__?: boolean;
  }
}
